import validate_email
from flask import request
from flask_restful import reqparse
from flask_restful.fields import MarshallingException
from flask_restful import Resource
from flask_user import current_user, login_required

from tank import api, app
from tank.contribs.user.models import UserProfile


def email(value, name):
    if validate_email.validate_email(value):
        return value
    raise MarshallingException("Not a valid email address")


def password(value, name):
    return value


def length_string(min_length=None, max_length=None):
    def validate(value, name):
        if min_length and min_length >= len(value):
            raise MarshallingException("value is too short")
        if max_length and max_length <= len(value):
            raise MarshallingException("value is too long")
        return value

    return validate


@api.resource('/user/session')
class UserCurrentResource(Resource):
    def get(self):
        profile = UserProfile.find_by_uid(current_user.id)
        if not profile.has_key("nickname"):
            profile.save({'nickname': current_user.email.split("@")[0]})
        return {
            'id': current_user.id,
            'first_name': current_user.first_name,
            'last_name': current_user.last_name,
            'nickname': current_user.nickname,
            'avatar': profile.get('avatar', app.config['DEFAULT_AVATAR'] + "?")
        }


@api.resource('/user/profile')
class UserProfileResource(Resource):
    decorators = [login_required]

    def get(self):
        # avatar, nickname, gender, location, signature
        return UserProfile.find_by_uid(current_user.id)

    def put(self):
        profile = UserProfile.find_by_uid(current_user.id)
        profile.save(request.json)
        return profile


@api.resource('/user/password')
class UserPasswordResource(Resource):
    def get(self):
        from tank.contribs.user import user_manager
        return "password" in request.args and user_manager.verify_password(request.args.get("password"), current_user)

    def put(self):
        from tank.contribs.user import user_manager
        old_password = request.json.get("oldPassword")
        new_password = request.json.get("newPassword")
        if old_password and user_manager.verify_password(old_password, current_user):
            hash_password = user_manager.hash_password(password=new_password)
            user_manager.update_password(current_user, hash_password)
        else:
            return "密码不正确", 400
